<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p><Back></Back>商家钱包</p>
    </header>

    <!-- 余额展示部分 -->
    <div class="balance-container">
      <div class="balance-title">钱包余额（元）</div>
      <div class="balance-amount">{{ balance }}</div>
    </div>

    <!-- 操作按钮 -->
    <div class="wallet-actions">
      <button class="recharge-btn" @click="showRechargeDialog = true">充值</button>
      <button class="withdraw-btn" @click="showWithdrawDialog = true">提现</button>
    </div>

    <!-- 交易记录列表 -->
    <div class="transactions-container">
      <div class="transactions-header">
        <span>交易记录</span>
        <div class="filter-buttons">
          <button :class="{ active: filter === 'all' }" @click="filter = 'all'">全部</button>
          <button :class="{ active: filter === 'income' }" @click="filter = 'income'">收入</button>
          <button :class="{ active: filter === 'expense' }" @click="filter = 'expense'">支出</button>
        </div>
      </div>
      <div class="transactions-list" v-if="filteredTransactions.length > 0">
        <div v-for="(item, index) in filteredTransactions" :key="index" class="transaction-item" @click="viewTransactionDetail(item)">
          <div class="transaction-left">
            <p class="transaction-title">{{ getTransactionDesc(item) }}</p>
            <p class="transaction-time">{{ formatTime(item.createTime) }}</p>
          </div>
          <div :class="['transaction-amount', isIncome(item) ? 'income' : 'expense']">
            ¥{{ getTransactionAmount(item) }}
          </div>
        </div>
      </div>
      <div class="empty-list" v-else>
        <p>暂无交易记录</p>
      </div>
    </div>

    <!-- 充值弹窗 -->
    <div class="dialog-overlay" v-if="showRechargeDialog">
      <div class="dialog-container">
        <div class="dialog-header">
          <h3>充值</h3>
          <span @click="showRechargeDialog = false" class="dialog-close">&times;</span>
        </div>
        <div class="dialog-content">
          <div class="form-item">
            <label>充值金额</label>
            <input type="number" v-model="rechargeAmount" placeholder="请输入充值金额">
          </div>
          <div class="form-item">
            <label>钱包密码</label>
            <input type="password" v-model="walletPassword" placeholder="请输入钱包密码">
          </div>
        </div>
        <div class="dialog-footer">
          <button @click="recharge" class="dialog-btn">确认充值</button>
        </div>
      </div>
    </div>

    <!-- 提现弹窗 -->
    <div class="dialog-overlay" v-if="showWithdrawDialog">
      <div class="dialog-container">
        <div class="dialog-header">
          <h3>提现</h3>
          <span @click="showWithdrawDialog = false" class="dialog-close">&times;</span>
        </div>
        <div class="dialog-content">
          <div class="form-item">
            <label>提现金额</label>
            <input type="number" v-model="withdrawAmount" placeholder="请输入提现金额">
          </div>
          <div class="form-item">
            <label>钱包密码</label>
            <input type="password" v-model="walletPassword" placeholder="请输入钱包密码">
          </div>
        </div>
        <div class="dialog-footer">
          <button @click="withdraw" class="dialog-btn">确认提现</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Back from '../components/Back.vue';

export default {
  name: 'BusinessWallet',
  components: {
    Back
  },
  data() {
    return {
      business: null,
      balance: '0.00',
      transactions: [],
      filter: 'all', // 'all', 'income', 'expense'
      showRechargeDialog: false,
      showWithdrawDialog: false,
      rechargeAmount: '',
      withdrawAmount: '',
      walletPassword: ''
    };
  },
  computed: {
    filteredTransactions() {
      if (this.filter === 'all') {
        return this.transactions;
      } else if (this.filter === 'income') {
        return this.transactions.filter(item => this.isIncome(item));
      } else {
        return this.transactions.filter(item => !this.isIncome(item));
      }
    }
  },
  created() {
    // 获取商家信息
    this.business = this.$getSessionStorage('business');
    if (!this.business) {
      alert('请先登录');
      this.$router.push({ path: '/businessLogin' });
      return;
    }
    
    // 获取钱包余额
    this.getBalance();
    
    // 获取交易记录
    this.getTransactions();
  },
  methods: {
    // 获取钱包余额
    getBalance() {
      let url = `WalletController/getBalance/${this.business.businessId}`;
      this.$axios.get(url).then(response => {
        if (response.data.code === 200) {
          this.balance = parseFloat(response.data.result || 0).toFixed(2);
        } else {
          alert('获取余额失败');
        }
      }).catch(error => {
        console.error('获取余额失败', error);
      });
    },
    
    // 获取交易记录
    getTransactions() {
      let url = `WalletController/listTransactionByWalletId/${this.business.businessId}`;
      this.$axios.get(url).then(response => {
        if (response.data.code === 200) {
          this.transactions = response.data.result || [];
        } else {
          alert('获取交易记录失败');
        }
      }).catch(error => {
        console.error('获取交易记录失败', error);
      });
    },
    
    // 充值
    recharge() {
      if (!this.rechargeAmount || this.rechargeAmount <= 0) {
        alert('请输入有效的充值金额');
        return;
      }
      
      if (!this.walletPassword) {
        alert('请输入钱包密码');
        return;
      }
      
      let url = `WalletController/recharge/${this.business.businessId}/${this.rechargeAmount}/${this.walletPassword}`;
      this.$axios.post(url).then(response => {
        if (response.data.code === 200) {
          alert('充值成功');
          this.showRechargeDialog = false;
          // 刷新余额和交易记录
          this.getBalance();
          this.getTransactions();
          // 清空表单
          this.rechargeAmount = '';
          this.walletPassword = '';
        } else {
          alert('充值失败: ' + response.data.message);
        }
      }).catch(error => {
        console.error('充值失败', error);
        alert('充值失败，请稍后重试');
      });
    },
    
    // 提现
    withdraw() {
      if (!this.withdrawAmount || this.withdrawAmount <= 0) {
        alert('请输入有效的提现金额');
        return;
      }
      
      if (!this.walletPassword) {
        alert('请输入钱包密码');
        return;
      }
      
      let url = `WalletController/withdraw/${this.business.businessId}/${this.withdrawAmount}/${this.walletPassword}`;
      this.$axios.post(url).then(response => {
        if (response.data.code === 200) {
          alert('提现成功');
          this.showWithdrawDialog = false;
          // 刷新余额和交易记录
          this.getBalance();
          this.getTransactions();
          // 清空表单
          this.withdrawAmount = '';
          this.walletPassword = '';
        } else {
          alert('提现失败: ' + response.data.message);
        }
      }).catch(error => {
        console.error('提现失败', error);
        alert('提现失败，请稍后重试');
      });
    },
    
    // 判断是否是收入
    isIncome(item) {
      return item.toWalletId == this.business.businessId;
    },
    
    // 获取交易金额
    getTransactionAmount(item) {
      return parseFloat(item.transactionAmount || 0).toFixed(2);
    },
    
    // 获取交易描述
    getTransactionDesc(item) {
      // 根据fromWalletId和toWalletId判断交易类型
      // 如果没有from，只有to，说明是充值
      if (!item.fromWalletId && item.toWalletId) {
        return '钱包充值';
      }
      // 如果有from，没有to，说明是提现
      else if (item.fromWalletId && !item.toWalletId) {
        return '钱包提现';
      }
      // 如果是自己付款
      else if (item.fromWalletId == this.business.businessId) {
        return '钱包提现';
      }
      // 如果是收款
      else if (item.toWalletId == this.business.businessId) {
        return '钱包充值';
      }
      else {
        return '交易';
      }
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())} ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}`;
    },
    
    padZero(num) {
      return num < 10 ? `0${num}` : num;
    },
    
    // 查看交易详情
    viewTransactionDetail(item) {
      this.$router.push({
        path: '/transactionDetail',
        query: {
          transactionId: item.transferId
        }
      });
    }
  }
};
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 余额展示部分 ******************/
.balance-container {
  margin-top: 16vw;
  padding: 6vw 4vw;
  background-color: #0097FF;
  color: #fff;
  text-align: center;
}

.balance-title {
  font-size: 4vw;
  margin-bottom: 2vw;
}

.balance-amount {
  font-size: 8vw;
  font-weight: bold;
}

/****************** 操作按钮 ******************/
.wallet-actions {
  display: flex;
  justify-content: space-between;
  padding: 4vw;
}

.wallet-actions button {
  width: 48%;
  height: 10vw;
  border: none;
  border-radius: 4px;
  font-size: 4vw;
  font-weight: bold;
}

.recharge-btn {
  background-color: #38CA73;
  color: #fff;
}

.withdraw-btn {
  background-color: #FF5252;
  color: #fff;
}

/****************** 交易记录列表 ******************/
.transactions-container {
  padding: 4vw;
  background-color: #fff;
  margin-top: 4vw;
  border-radius: 8px;
  margin-left: 4vw;
  margin-right: 4vw;
}

.transactions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 3vw;
  border-bottom: 1px solid #f0f0f0;
}

.transactions-header span {
  font-size: 4.5vw;
  font-weight: bold;
  color: #333;
}

.filter-buttons {
  display: flex;
  gap: 2vw;
}

.filter-buttons button {
  padding: 1vw 2vw;
  background-color: #f0f0f0;
  border: none;
  border-radius: 3px;
  font-size: 3vw;
  color: #666;
}

.filter-buttons button.active {
  background-color: #0097FF;
  color: #fff;
}

.transactions-list {
  margin-top: 2vw;
}

.transaction-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 3vw 0;
  border-bottom: 1px solid #f5f5f5;
}

.transaction-left {
  flex: 1;
}

.transaction-title {
  font-size: 4vw;
  color: #333;
  margin-bottom: 1vw;
}

.transaction-time {
  font-size: 3vw;
  color: #999;
}

.transaction-amount {
  font-size: 4.5vw;
  font-weight: bold;
}

.transaction-amount.income {
  color: #38CA73;
}

.transaction-amount.expense {
  color: #FF5252;
}

.empty-list {
  text-align: center;
  padding: 10vw 0;
  color: #999;
}

/****************** 弹窗样式 ******************/
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  z-index: 2000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-container {
  width: 80%;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.dialog-header {
  padding: 3vw 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.dialog-header h3 {
  font-size: 4.5vw;
  color: #333;
  margin: 0;
}

.dialog-close {
  font-size: 6vw;
  color: #999;
  cursor: pointer;
}

.dialog-content {
  padding: 4vw;
}

.form-item {
  margin-bottom: 3vw;
}

.form-item label {
  display: block;
  margin-bottom: 2vw;
  font-size: 3.8vw;
  color: #333;
}

.form-item input {
  width: 100%;
  padding: 2.5vw;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 3.8vw;
  box-sizing: border-box;
}

.dialog-footer {
  padding: 3vw 4vw;
  border-top: 1px solid #f0f0f0;
}

.dialog-btn {
  width: 100%;
  padding: 2.5vw;
  background-color: #0097FF;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 4vw;
}
</style> 